package com.base.leetcode;

/**
 * @Author: hdhao
 * @Create: 2023/3/30 - 20:53
 * @Version: v1.0
 */
//判断回文链表(从左往右 和 从右往左 读 是一样的)
public class Leetcode234 {
    /**
     * 步骤1 找中间点
     * 步骤2 中间点后半个链表反转
     * 步骤3 反转后链表与原链表逐一比较
     * @param
     * @return
     */
    public boolean isPalindrome(ListNode head){
        ListNode middle = middle(head);
        ListNode newHead = reverse(middle);
        //3.比较
        while (newHead!=null){
            if (newHead.val != head.val) {
                return false;
            }
            newHead = newHead.next;
            head = head.next;
        }
        return true;
    }
    //2.反转链表
    private ListNode reverse(ListNode o1){
        ListNode n1 = null;
        while (o1 !=null){
            ListNode o2 = o1.next;
            o1.next = n1;
            n1 = o1;
            o1 = o2;
        }
        return n1;
    }
    //1.找中间节点
    private ListNode middle(ListNode head){
        ListNode p1 = head;
        ListNode p2 = head;
        while (p2!=null && p2.next!=null){
            p1 = p1.next;
            p2 = p2.next.next;
        }
        return p1;
    }
}
